package myservice.android;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

import myservice.android.database.Database;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.text.Editable;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class Global {
	
	public final static String TAG = "MYSERVICE";
	public final static String databaseName = "MyServiceDB";
	public final static int databaseVersion = 2; // Increment every time database is changed
	
	public final static long TIMESTAMP_DELETED = 9999999999999L; // Marks a deleted row in a database; needs to be preserved for synchronization purposes	
	
	// If true, folder "MyService" exists on the SD card
	public static boolean folderMyServiceExists = false;
	
	// Configuration settings
	public static int firstDayOfWeek;
	public static boolean trackCreditTime;
	public static boolean showInactives;
	public static boolean autoIncrementReturnCalls;
	public static boolean autoBackupData;
	public static int dateFormat;
	public static int addressFormat;
	public static int yearRange;	
	public static String smsTemplate;
	
	// Graph settings
	public static int fromMonth,fromYear,toMonth,toYear;
	public static boolean showMagazinesGraph,showBooksGraph,showBrochuresGraph,showReturnCallsGraph,showBibleStudentsGraph,showTotalTimeGraph,showMinistryTimeGraph,showCreditTimeGraph;
	
	public static String[] monthNames, monthNamesShort; // These are loaded in the CalendarActivity
	
	public static long selectedId; // for storing a selected record from various lists
	public static int selectedType; // to differentiate whether a house or apartment was selected from a list; 0=interested, 1=house/apartment, 2=date
	public static int selectedDate, selectedMonth, selectedYear;
	
    public static Resources res;
	
	/** Loads settings from database into memory */
	public static void loadSettings() {
		
		Log.i(TAG,"Loading settings...");		
		
    	Cursor cursor = Database.select("SELECT * FROM settings");
    	while (cursor.moveToNext()) {
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("firstdayofweek"))
    			firstDayOfWeek=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("showinactives")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				showInactives=true;
    			else
    				showInactives=false;
    		}
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("trackcredittime")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				trackCreditTime=true;
    			else
    				trackCreditTime=false;
    		}
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("autoincrementreturncalls")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				autoIncrementReturnCalls=true;
    			else
    				autoIncrementReturnCalls=false;
    		}    	
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("autobackup")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				autoBackupData=true;
    			else
    				autoBackupData=false;
    		}      		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("smstemplate"))
    			smsTemplate=cursor.getString(cursor.getColumnIndex("value"));    		   		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("dateformat"))
    			dateFormat=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));    		
	
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("addressformat"))
    			addressFormat=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));   
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("yearrange"))
    			yearRange=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));      		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("showtotaltimegraph")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				showTotalTimeGraph=true;
    			else
    				showTotalTimeGraph=false;
    		}    
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("showministrytimegraph")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				showMinistryTimeGraph=true;
    			else
    				showMinistryTimeGraph=false;
    		}
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("showcredittimegraph")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				showCreditTimeGraph=true;
    			else
    				showCreditTimeGraph=false;
    		}
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("showmagazinesgraph")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				showMagazinesGraph=true;
    			else
    				showMagazinesGraph=false;
    		}    		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("showbrochuresgraph")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				showBrochuresGraph=true;
    			else
    				showBrochuresGraph=false;
    		}    		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("showbooksgraph")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				showBooksGraph=true;
    			else
    				showBooksGraph=false;
    		}    
    		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("showreturncallsgraph")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				showReturnCallsGraph=true;
    			else
    				showReturnCallsGraph=false;
    		}
    		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("showbiblestudentsgraph")) {
    			if (cursor.getString(cursor.getColumnIndex("value")).equals("true"))
    				showBibleStudentsGraph=true;
    			else
    				showBibleStudentsGraph=false;
    		}    
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("graphsfrommonth"))
    			fromMonth=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));    		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("graphsfromyear"))
    			fromYear=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));    		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("graphstomonth"))
    			toMonth=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));    		
    		
    		if (cursor.getString(cursor.getColumnIndex("name")).equals("graphstoyear"))
    			toYear=Integer.parseInt(cursor.getString(cursor.getColumnIndex("value")));    		
    		
    	}
    	
    	cursor.close();
	}
	
	/** Saves settings from memory to database */
	public static void saveSettings() {
		
		Log.i(TAG,"Saving settings...");
		
		String value;
		
		Database.execSQL("UPDATE settings SET value='"+firstDayOfWeek+"' WHERE name='firstdayofweek'");

		if (showInactives==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='showinactives'");
		
		if (trackCreditTime==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='trackcredittime'");		
		
		if (autoIncrementReturnCalls==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='autoincrementreturncalls'");
		
		if (autoBackupData==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='autobackup'");		
		
		Database.execSQL("UPDATE settings SET value='"+dateFormat+"' WHERE name='dateformat'");
		
		Database.execSQL("UPDATE settings SET value='"+addressFormat+"' WHERE name='addressformat'");
		
		Database.execSQL("UPDATE settings SET value='"+yearRange+"' WHERE name='yearrange'");		
		
		Database.execSQL("UPDATE settings SET value='"+smsTemplate+"' WHERE name='smstemplate'");		
		
		if (showTotalTimeGraph==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='showtotaltimegraph'");
		
		if (showMinistryTimeGraph==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='showministrytimegraph'");
		
		if (showCreditTimeGraph==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='showcredittimegraph'");
		
		if (showMagazinesGraph==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='showmagazinesgraph'");
		
		if (showBooksGraph==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='showbooksgraph'");
		
		if (showBrochuresGraph==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='showbrochuresgraph'");
		
		if (showReturnCallsGraph==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='showreturncallsgraph'");
		
		if (showBibleStudentsGraph==false)
			value="false";
		else
			value="true";		
		Database.execSQL("UPDATE settings SET value='"+value+"' WHERE name='showbiblestudentsgraph'");
		
		Database.execSQL("UPDATE settings SET value='"+fromMonth+"' WHERE name='graphsfrommonth'");		
		
		Database.execSQL("UPDATE settings SET value='"+fromYear+"' WHERE name='graphsfromyear'");		
		
		Database.execSQL("UPDATE settings SET value='"+toMonth+"' WHERE name='graphstomonth'");		
		
		Database.execSQL("UPDATE settings SET value='"+toYear+"' WHERE name='graphstoyear'");		
		
	}
	
	/** Returns date formatted according to the option selected in settings */
	public static String getFormattedDate(int year, int month, int date) {
				
		Calendar c = Calendar.getInstance();
		
		// Check if the date is today
		if (c.get(Calendar.DATE)==date && c.get(Calendar.MONTH)==month && c.get(Calendar.YEAR)==year)
			return res.getString(R.string.label_today);
		
		c.set(year,month,date);
		
		String[] dateFormats = Global.res.getStringArray(R.array.array_date_formats);
		String pattern = new String(dateFormats[Global.dateFormat]);
		pattern = pattern.replace("YEAR", "yyyy").replace("MONTH", "MM").replace("DATE", "dd");		
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);    	
    	return sdf.format(c.getTime());
		
	}
	
	/** Returns address formatted according to the option selected in settings */
	public static String getFormattedAddress(String house, String street, String town) {
		
		String address="";
		
		if (house==null)
			house="";
		if (street==null)
			street="";
		if (town==null)
			town="";
		if (!house.equals("") && !street.equals("")) {
			if (Global.addressFormat==0)
				address=house+" "+street;
			else
				address=street+" "+house;
		} else if (!house.equals(""))
			address=house;
		else if (!street.equals(""))
			address=street;
		
		if (!town.equals("")) {
			if (!address.equals(""))
				address=address+", "+town;
			else
				address=town;
		}
		
		return address;
	}
	
	public static void displayToast(Context context, String message) {
		
		Toast toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);
		if (message.length()>30)
			toast.setDuration(Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();		
		
	}
	
	public static long getTimeStamp() {
		return System.currentTimeMillis();
	}
	
	// Generates a random integer to be used as identifier between synchronized parties
	public static int getRandomSyncId() {
		Random randomGenerator = new Random();
		return randomGenerator.nextInt(9000)+1000;
	}	
	
	public static boolean copyFile(String sourceFile, String destinationFile) {
		
		File fromFile = new File(sourceFile);
		File toFile = new File(destinationFile);
		
		if (fromFile.exists()==false) {
			Log.w(Global.TAG,"Cannot copy the file '"+fromFile.getName()+"' because it does not exist.");
			return false;
		}
		
		InputStream inStream = null;
		OutputStream outStream = null;
 
    	try {
 
    	    inStream = new FileInputStream(fromFile);
    	    outStream = new FileOutputStream(toFile);
 
    	    byte[] buffer = new byte[1024];
 
    	    int length;
    	    while ((length = inStream.read(buffer)) > 0) {
    	    	outStream.write(buffer, 0, length); 
    	    }
 
    	    inStream.close();
    	    outStream.close();
 
    	} catch (Exception e){
    		Log.e(Global.TAG,e.getMessage());
    		return false;
    	}		
    	
    	Log.i(Global.TAG,"Copied file '"+sourceFile+"' to '"+destinationFile+"'.");
    	
    	return true;
    	
	}
	
	public static String fixText(Editable original) {
		if (original==null)
			return null;
		String input = original.toString();
		return input.replaceAll("'", "`");
	}	
	
	public static String showNewItemDialog(Context context, String title, String label) {
		final Dialog dialog = new Dialog(context);
		dialog.setContentView(R.layout.add_person_dialog);
		dialog.setTitle(title);
		
		Button saveButton = (Button) dialog.findViewById(R.id.saveButton);
		saveButton.setText(Global.res.getString(R.string.button_add));
		
		Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
		cancelButton.setText(Global.res.getString(R.string.button_cancel));		
		
		saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog.dismiss();				
			}			
		});
		
		cancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialog.dismiss();				
			}			
		});		
		
		dialog.show();
		
		return null;
	}

}
